package com.vending.service.impl;

import com.vending.mapper.*;
import com.vending.service.DashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VendingMachineMapper machineMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Override
    public Map<String, Object> getDashboardData() {
        Map<String, Object> data = new HashMap<>();

        // 统计数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalUsers", userMapper.countAll());
        statistics.put("newUsers", userMapper.countTodayNewUsers());
        statistics.put("totalMachines", machineMapper.countAll());
        statistics.put("onlineMachines", machineMapper.countByStatus("NORMAL"));
        statistics.put("todayOrders", orderMapper.countTodayOrders());
        statistics.put("todayAmount", orderMapper.sumTodayAmount());
        statistics.put("pendingOrders", workOrderMapper.countByStatus("PENDING"));
        statistics.put("totalOrders", workOrderMapper.countAll());

        // 订单趋势数据（近7天）
        Map<String, Object> orderTrend = getOrderTrend();
        
        // 销售额分布数据
        List<Map<String, Object>> salesDistribution = getSalesDistribution();

        data.put("statistics", statistics);
        data.put("orderTrend", orderTrend);
        data.put("salesDistribution", salesDistribution);

        return data;
    }

    private Map<String, Object> getOrderTrend() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        List<String> dates = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();

        // 获取近7天的日期
        for (int i = 6; i >= 0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            dates.add(date.format(formatter));
            counts.add(orderMapper.countOrdersByDate(date));
        }

        Map<String, Object> trend = new HashMap<>();
        trend.put("dates", dates);
        trend.put("counts", counts);
        return trend;
    }

    private List<Map<String, Object>> getSalesDistribution() {
        return orderMapper.getProductSalesDistribution().stream()
            .map(item -> {
                Map<String, Object> map = new HashMap<>();
                map.put("name", item.get("productName"));
                map.put("value", item.get("amount"));
                return map;
            })
            .collect(Collectors.toList());
    }
} 